package com.guodi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @描述：排序工具
 * @作者：汤厚韬
 * @日期：2021/3/16 10:18
 */
public class SortListUtil<T> {

    private final static Logger logger = LoggerFactory.getLogger(SortListUtil.class);

    public static <T> void sort(List<T> list ,final String method, final String sort){
        Collections.sort(list, new Comparator<T>() {
            @Override
            public int compare(T a, T b) {
                int ret = 0;
                try{
                    Method m1 = a.getClass().getMethod(method, null);
                    Method m2 = b.getClass().getMethod(method, null);
                    if(sort != null && "desc".equalsIgnoreCase(sort)){
                        // 倒序
                        ret = compareTo(m2.invoke(b, null),m1.invoke(a, null));
                    }else{
                        // 正序
                        ret = compareTo(m1.invoke(a, null),m2.invoke(b, null));
                    }
                }catch (NoSuchMethodException noSuchMethodException){
                    logger.error(noSuchMethodException.getMessage(),noSuchMethodException);
                } catch (IllegalAccessException illegalAccessException) {
                    logger.error(illegalAccessException.getMessage(),illegalAccessException);
                } catch (InvocationTargetException invocationTargetException) {
                    logger.error(invocationTargetException.getMessage(),invocationTargetException);
                }
                return ret;
            }
        });
    }


    public static int compareTo(Object a,Object b){
        if (a.getClass().getName().equals(b.getClass().getName())) {
            // 如果类型相同
            if (a instanceof Integer){
                return a == b ? 0: (Integer)a - (Integer)b;
            }else if(a instanceof Long){
                return a == b ? 0: (Long)a > (Long)b? 1:-1;
            }else if(a instanceof Float){
                return Math.abs((Float)a - (Float)b) < 0.00000001 ? 0: (Float)a > (Float)b? 1:-1;
            }else if(a instanceof Double){
                return Math.abs((Double)a - (Double)b) < 0.00000001 ? 0: (Double)a > (Double)b? 1:-1;
            }else if(a instanceof Comparable){
                // 如果实现了Comparable接口，直接调接口比较
                return ((Comparable)a).compareTo(b);
            }else {
                return a.toString().compareTo(b.toString());
            }
        }else {
            // 如果类型不相同，直接当字符串比较
            return a.toString().compareTo(b.toString());
        }
    }
}


